package com.cu.current;

import java.util.concurrent.CyclicBarrier;

public class CyclicbarrierDemo{

    private  static int i = 0;

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
            @Override
            public void run() {
                System.out.println("all end");
            }
        });


        Thread thread1 = getThread(cyclicBarrier);

        Thread thread2 = getThread(cyclicBarrier);

        thread1.start();
        thread2.start();
        try {
            cyclicBarrier.await();
            System.out.println("main start");
        } catch (Exception e) {
            e.printStackTrace();
        }
        cyclicBarrier.reset();

        Thread thread3 = getThread(cyclicBarrier);
        Thread thread4 = getThread(cyclicBarrier);
        thread3.start();
        thread4.start();

        try {
            cyclicBarrier.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Thread getThread(CyclicBarrier cyclicBarrier){
        Thread thread2 = new Thread(new Runnable() {
            String name = "thread" + i++;
            @Override
            public void run() {
                try {
                    System.out.println(name + " start");
                    Thread.sleep(100);
                    System.out.println(name + " sleep end");
                    cyclicBarrier.await();
                    System.out.println(name + " end");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        return thread2;
    }
}
